<template>
  <div class="min-h-screen bg-gradient-to-br from-gray-50 via-white to-blue-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold text-gray-900 mb-4">历史记录</h1>
        <p class="text-xl text-gray-600">查看和管理您的所有会议记录</p>
      </div>

      <!-- Filters -->
      <div class="card p-6 mb-8">
        <div class="flex flex-col lg:flex-row gap-6">
          <!-- Search -->
          <div class="flex-1">
            <div class="relative">
              <Search class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
              <input
                v-model="searchQuery"
                type="text"
                class="input-field pl-10"
                placeholder="搜索会议标题或描述..."
              />
            </div>
          </div>

          <!-- Status Filter -->
          <div class="lg:w-48">
            <select
              v-model="statusFilter"
              class="input-field"
            >
              <option value="">全部状态</option>
              <option value="recording">录音中</option>
              <option value="processing">处理中</option>
              <option value="completed">已完成</option>
            </select>
          </div>

          <!-- Date Range -->
          <div class="lg:w-48">
            <input
              v-model="dateFilter"
              type="date"
              class="input-field"
              placeholder="选择日期"
            />
          </div>

          <!-- Clear Filters -->
          <button
            @click="clearFilters"
            class="btn-secondary px-4 py-2"
          >
            清除筛选
          </button>
        </div>
      </div>

      <!-- Statistics -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="card p-6 text-center">
          <div class="text-3xl font-bold text-primary-600 mb-2">
            {{ totalMeetings }}
          </div>
          <div class="text-gray-600">总会议数</div>
        </div>

        <div class="card p-6 text-center">
          <div class="text-3xl font-bold text-green-600 mb-2">
            {{ completedMeetings }}
          </div>
          <div class="text-gray-600">已完成</div>
        </div>

        <div class="card p-6 text-center">
          <div class="text-3xl font-bold text-yellow-600 mb-2">
            {{ processingMeetings }}
          </div>
          <div class="text-gray-600">处理中</div>
        </div>

        <div class="card p-6 text-center">
          <div class="text-3xl font-bold text-red-600 mb-2">
            {{ recordingMeetings }}
          </div>
          <div class="text-gray-600">录音中</div>
        </div>
      </div>

      <!-- Meetings List -->
      <div class="card">
        <div class="p-6 border-b border-gray-200">
          <div class="flex items-center justify-between">
            <h2 class="text-lg font-semibold text-gray-900">
              会议列表 ({{ filteredMeetings.length }})
            </h2>
            <div class="flex items-center gap-2">
              <button
                @click="refreshMeetings"
                :disabled="loading"
                class="text-primary-600 hover:text-primary-700 p-2 hover:bg-primary-50 rounded-lg transition-colors"
              >
                <RefreshCw :class="{ 'animate-spin': loading }" class="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>

        <!-- Loading State -->
        <div v-if="loading" class="p-12 text-center">
          <Loader2 class="w-8 h-8 animate-spin text-primary-600 mx-auto mb-4" />
          <p class="text-gray-600">加载中...</p>
        </div>

        <!-- Empty State -->
        <div v-else-if="filteredMeetings.length === 0" class="p-12 text-center">
          <FileX class="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <p class="text-gray-500 mb-6">
            {{ searchQuery || statusFilter || dateFilter ? '没有找到匹配的会议' : '暂无会议记录' }}
          </p>
          <div class="flex gap-4 justify-center">
            <router-link to="/record" class="btn-primary">
              开始录音
            </router-link>
            <router-link to="/upload" class="btn-secondary">
              上传音频
            </router-link>
          </div>
        </div>

        <!-- Meetings Grid -->
        <div v-else class="p-6">
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div
              v-for="meeting in filteredMeetings"
              :key="meeting.id"
              class="border border-gray-200 rounded-lg p-6 hover:shadow-lg transition-all duration-300 hover:border-primary-300 cursor-pointer group"
              @click="goToMeeting(meeting.id)"
            >
              <!-- Header -->
              <div class="flex items-start justify-between mb-4">
                <div class="flex-1 mr-3">
                  <h3 class="text-lg font-semibold text-gray-900 mb-1 group-hover:text-primary-600 transition-colors">
                    {{ meeting.title }}
                  </h3>
                  <p v-if="meeting.description" class="text-gray-600 text-sm line-clamp-2">
                    {{ meeting.description }}
                  </p>
                </div>
                <div class="flex items-center gap-2">
                  <div
                    class="px-2 py-1 text-xs rounded-full"
                    :class="getStatusClass(meeting.status)"
                  >
                    {{ getStatusText(meeting.status) }}
                  </div>
                  <button
                    @click.stop="deleteMeeting(meeting.id)"
                    class="opacity-0 group-hover:opacity-100 text-red-600 hover:text-red-700 p-1 hover:bg-red-50 rounded transition-all duration-200"
                  >
                    <Trash2 class="w-4 h-4" />
                  </button>
                </div>
              </div>

  <!-- Meta Info -->
              <div class="space-y-2 text-sm text-gray-500">
                <div class="flex items-center gap-2">
                  <Calendar class="w-4 h-4" />
                  <span>{{ formatDate(meeting.created_at) }}</span>
                </div>

                <div v-if="meeting.duration" class="flex items-center gap-2">
                  <Clock class="w-4 h-4" />
                  <span>{{ formatDuration(meeting.duration) }}</span>
                </div>

                <div class="flex items-center gap-2">
                  <FileText class="w-4 h-4" />
                  <span>{{ meeting.transcription ? '已转录' : '等待转录' }}</span>
                </div>

                <div class="flex items-center gap-2">
                  <FileCheck class="w-4 h-4" />
                  <span>{{ meeting.minutes ? '已生成纪要' : '等待生成' }}</span>
                </div>
              </div>

              <!-- Preview Snippets -->
              <div v-if="meeting.transcription || meeting.minutes" class="mt-3 pt-3 border-t border-gray-100">
                <div v-if="meeting.transcription" class="mb-2">
                  <p class="text-xs text-gray-500 mb-1">转录预览:</p>
                  <p class="text-sm text-gray-700 line-clamp-2">{{ meeting.transcription.text?.substring(0, 100) }}...</p>
                </div>
                <div v-if="meeting.minutes">
                  <p class="text-xs text-gray-500 mb-1">纪要预览:</p>
                  <p class="text-sm text-gray-700 line-clamp-2">{{ meeting.minutes.content?.substring(0, 100) }}...</p>
                </div>
              </div>

              <!-- Action Buttons -->
              <div class="mt-4 pt-4 border-t border-gray-100 flex gap-2">
                <button
                  @click.stop="goToMeeting(meeting.id)"
                  class="flex-1 text-primary-600 hover:text-primary-700 text-sm font-medium py-2 px-3 rounded hover:bg-primary-50 transition-colors"
                >
                  查看详情
                </button>
                <button
                  v-if="meeting.status === 'completed'"
                  @click.stop="downloadMinutes(meeting.id)"
                  class="text-gray-600 hover:text-gray-700 p-2 hover:bg-gray-50 rounded transition-colors"
                >
                  <Download class="w-4 h-4" />
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMeetingStore } from '@/stores/meeting'
import { getMinutes } from '@/services/api'
import type { Meeting } from '@/types'
import {
  Search,
  RefreshCw,
  Loader2,
  FileX,
  Trash2,
  Calendar,
  Clock,
  FileText,
  FileCheck,
  Download
} from 'lucide-vue-next'

const router = useRouter()
const meetingStore = useMeetingStore()

// Filters
const searchQuery = ref('')
const statusFilter = ref('')
const dateFilter = ref('')
const loading = ref(false)

// Computed
const meetings = computed(() => meetingStore.meetings)

const filteredMeetings = computed(() => {
  let filtered = meetings.value

  // Search filter
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(meeting =>
      meeting.title.toLowerCase().includes(query) ||
      (meeting.description && meeting.description.toLowerCase().includes(query))
    )
  }

  // Status filter
  if (statusFilter.value) {
    filtered = filtered.filter(meeting => meeting.status === statusFilter.value)
  }

  // Date filter
  if (dateFilter.value) {
    const filterDate = new Date(dateFilter.value)
    filtered = filtered.filter(meeting => {
      const meetingDate = new Date(meeting.created_at).toDateString()
      return meetingDate === filterDate.toDateString()
    })
  }

  // Sort by date (newest first)
  return filtered.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
})

// Statistics
const totalMeetings = computed(() => meetings.value.length)
const completedMeetings = computed(() => meetings.value.filter(m => m.status === 'completed').length)
const processingMeetings = computed(() => meetings.value.filter(m => m.status === 'processing').length)
const recordingMeetings = computed(() => meetings.value.filter(m => m.status === 'recording').length)

// Methods
const refreshMeetings = async () => {
  loading.value = true
  try {
    await meetingStore.fetchMeetings()
  } finally {
    loading.value = false
  }
}

const clearFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  dateFilter.value = ''
}

const goToMeeting = (id: string) => {
  router.push(`/meeting/${id}`)
}

const deleteMeeting = async (id: string) => {
  if (confirm('确定要删除这个会议吗？此操作不可撤销。')) {
    try {
      await meetingStore.removeMeeting(id)
    } catch (error) {
      console.error('Failed to delete meeting:', error)
    }
  }
}

const downloadMinutes = async (meetingId: string) => {
  try {
    const minutes = await getMinutes(meetingId)
    if (minutes.content) {
      const blob = new Blob([minutes.content], { type: 'text/markdown' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `meeting-minutes-${new Date().toISOString().split('T')[0]}.md`
      a.click()
      URL.revokeObjectURL(url)
    }
  } catch (error) {
    console.error('Failed to download minutes:', error)
  }
}

const getStatusClass = (status: string) => {
  switch (status) {
    case 'recording':
      return 'bg-red-100 text-red-800'
    case 'processing':
      return 'bg-yellow-100 text-yellow-800'
    case 'completed':
      return 'bg-green-100 text-green-800'
    default:
      return 'bg-gray-100 text-gray-800'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'recording':
      return '录音中'
    case 'processing':
      return '处理中'
    case 'completed':
      return '已完成'
    default:
      return '未知'
  }
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDuration = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

onMounted(() => {
  refreshMeetings()
})
</script>